package io.sage.common.utils;

/**
 * 根据前六位数生成crc四位代码方法
 * @author xujh
 *
 */

public class CRC16 {

	public static void main(String[] args) {
	        String str1 = "01 03 00 00 00 02";

	        System.out.println(CRC16(hex_to_ten(str1)));
	    }
	    public static int[] hex_to_ten(String hexString) {
	        hexString = hexString.replaceAll(" ", "");

	        int len = hexString.length();
	        int index = 0;
	        int[] ten = new int[len / 2];

	        while (index < len) {
	            String sub = hexString.substring(index, index + 2);
	            ten[index / 2] = Integer.parseInt(sub, 16);
	            index += 2;
	        }
	        return ten;
	    }

	    public static String CRC16(int[] Buf) {
	        int CRC = 0xffff;
	        int i, j;
	        int len = Buf.length;

	        for (i = 0; i < len; i++) {
	            CRC = CRC ^ (Buf[i] & 0xff);
	            for (j = 0; j < 8; j++) {
	                if ((CRC & 0x01) == 1)
	                    CRC = (CRC >> 1) ^ 0xA001;
	                else
	                    CRC = CRC >> 1;
	            }
	        }

	        CRC = ( (CRC & 0x0000FF00) >> 8) | ( (CRC & 0x000000FF ) << 8);
	        
	        return Integer.toHexString(CRC);
	    }
}
